package gatperdut.chato.lucene.search;

import gatperdut.chato.constants.CSConstantsLucene;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.analysis.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

public class CMSearcher {

    private static IndexSearcher indexSearcher;

    private final static QueryParser parser = new QueryParser( Version.LUCENE_35, CSConstantsLucene.FIELD_CATCH_ALL, new SimpleAnalyzer( Version.LUCENE_35 ) );

    static {
        try {
            URL indexesFileURL = new URL("file", "localhost", CSConstantsLucene.INDEX_PATH );
            File f = new File( indexesFileURL.toURI() );
            Directory indexDir = FSDirectory.open( f );
            indexSearcher = new IndexSearcher( IndexReader.open( indexDir ) );
        }
        catch ( IOException e ) {
            e.printStackTrace();
        }
        catch ( URISyntaxException e ) {
            e.printStackTrace();
        }
    }

    public static Map<Integer, Document> getRelatedDocuments( String[] seeAlso ) {
        Map<Integer, Document> related = new HashMap<Integer, Document>();
        Term t;
        Query q;
        TopDocs td;
        for ( String s : seeAlso ) {
            t = new Term( CSConstantsLucene.FIELD_TITLE, s );
            q = new TermQuery( t );
            try {
                td = getIndexSearcher().search( q, 1 );
                if ( td.totalHits == 1 ) {
                    related.put( td.scoreDocs[0].doc, getIndexSearcher().doc( td.scoreDocs[0].doc ) );
                }
            }
            catch ( IOException e ) {
                e.printStackTrace();
            }
        }

        return related;
    }

    public static IndexSearcher getIndexSearcher() {
        return indexSearcher;
    }

    public static QueryParser getParser() {
        return parser;
    }

    @Override
    protected void finalize() throws Throwable {
        indexSearcher.close();
        super.finalize();
    }

}
